﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EC;
namespace siqi.Logic.Dispatch
{
    public class Dispatcher
    {
        public Dispatcher()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(Run);
        }
        public Interfaces.ISiqiServer Server
        {
            get;
            set;
        }

        private Queue<IJob> mQueue = new Queue<IJob>();

        public void Add(IJob item)
        {
            lock (this)
            {
                mQueue.Enqueue(item);
            }
        }

        public IJob GetItem()
        {
            lock (this)
            {
                if (mQueue.Count > 0)
                    return mQueue.Dequeue();
                return default(IJob);
            }
        

        }

        public void Run(object state)
        {

            while (true)
            {
                try
                {
                    IJob job = GetItem();

                    if (job != null)
                    {
                        job.Execute();
                    }
                    else
                        System.Threading.Thread.Sleep(10);
                }
                catch (Exception e_)
                {
                    "{0} invoke error {1}".Log4Error(e_, typeof(IJob), e_.Message);
                }
            }
        }
    }
}
